package com.mike.fragmentdemo3.Fragment.Activity;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.mike.fragmentdemo3.Fragment.Service.MusicService;
import com.mike.fragmentdemo3.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;


public class MainActivity extends AppCompatActivity {

    private int mPlayModeState = 0; // 0顺序， 1循环， 3随机
    private CircleMenu circleMenu;
    //private ImageView mIvPlaySpeed;
    private TextView mTvPlaySpeed;
    private ImageView mMapIv;
    private AudioManager mAudioManager;
    private ImageView mIvPlayMode;
    private ImageView mSmartHomeIv;
    private TextView mTvPlayMode;
    private TextView mDeviceNum;
    private Context context;
    private static ImageView sIvRecord; //歌曲图片
    private static SeekBar sSeekBar; //进度条播放
    private static TextView sCurrentTv; //目前进度
    private static TextView sTotalTv; //总进度
    private static TextView sTvName; //歌曲名
    private static TextView sTvSinger; //歌手名
    private Button mBtnPlay; //播放/暂停按钮
    private Button mBtnPre; //上一首按钮
    private Button mBtnNext; //下一首按钮
    private TextView mCurrentTimeTv;
    private ObjectAnimator mAnimator; //歌曲图片动画机
    private MusicService.MusicControl mControl; //音乐service服务类
    private int mStateFlag = 0; //播放标志位。0开始播放，1停止播放，2继续播放
    private static final String TAG = "MainActivity"; //打印日志
    private boolean mIsServiceConnected = false; //服务是否连接标志位
    private ImageView mIvSmartHome; //主页面智能家居模块图片
    private ImageView mIncreaseVolumeIv;
    private ImageView mReduceVolumeIv;
    private ImageView mVolumeIv;
    // 创建一个SharedPreferences.OnSharedPreferenceChangeListener的实例变量
    private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
    private boolean flagVolume = true;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected" + service);
            mControl = (MusicService.MusicControl) service;
            mControl.registerPlayInfoChange(new MusicService.OnPlayInfoListener() {
                @Override
                public void onPlayInfo(Bundle data) {
                    String name = data.getString("name");
                    String singer = data.getString("singer");
                    int image = data.getInt("image");
                    int duration = data.getInt("duration");
                    int currentPosition = data.getInt("currentPosition");
                    String totalTime = msToMinSec(duration);
                    String currentTime = msToMinSec(currentPosition);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 更新UI组件
                            if (image != 0) { // 检查image是否为有效的资源ID
                                Glide.with(context)
                                        .load(image)
                                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                        .into(sIvRecord);
                            }
                            sTvName.setText(name);
                            sTvSinger.setText(singer);
                            sSeekBar.setMax(duration); //设置seekBar的最大值
                            sSeekBar.setProgress(currentPosition); //设置seekbar的进度位置
                            sTotalTv.setText(totalTime);
                            sCurrentTv.setText(currentTime);
                        }
                    });


                }
            });
            // 获取并显示第一首歌的信息
            Bundle firstSongInfo = mControl.getFirstSongInfo();
            if (firstSongInfo != null) {
                runOnUiThread(() -> {
                    String firstName = firstSongInfo.getString("name");
                    String firstSinger = firstSongInfo.getString("singer");
                    int image = firstSongInfo.getInt("image");
                    int duration = firstSongInfo.getInt("duration");

                    sTvName.setText(firstName);
                    sTvSinger.setText(firstSinger);
                    if (image != 0) {
                        Glide.with(context)
                                .load(image)
                                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                .into(sIvRecord);
                    }
                    sSeekBar.setMax(duration);
                    sSeekBar.setProgress(0); // 初始进度为0
                    sTotalTv.setText(msToMinSec(duration));
                    sCurrentTv.setText("00:00");
                });
            }


            mIsServiceConnected = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mControl = null;
            mIsServiceConnected = false;
        }
    };

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            updateDeviceCount();
            return insets;
        });
        init();
    }


    private void setSpinnerSelectionByValue(Spinner spinner, float speed) {
        ArrayAdapter<CharSequence> adapter = (ArrayAdapter<CharSequence>) spinner.getAdapter();
        for (int i = 0; i < adapter.getCount(); i++) {
            String item = adapter.getItem(i).toString();
            // 假设你的速度值后面跟着一个'x'，例如"0.5x"
            if (item.endsWith("x")) {
                item = item.substring(0, item.length() - 1);
            }
            if (Float.parseFloat(item) == speed) {
                spinner.setSelection(i);
                return;
            }
        }
        // 如果没有找到匹配的速度值，可以选择默认项（例如第一项）
        spinner.setSelection(1);
    }

    private void showSpeedPopup(View anchor) {
        PopupMenu popup = new PopupMenu(this, anchor);
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.menu_speed, popup.getMenu());

        popup.setOnMenuItemClickListener(item -> {
            String speed = item.getTitle().toString().substring(0, item.getTitle().length() - 1);
            float speedFloat = Float.parseFloat(speed);
            if (mControl != null && mIsServiceConnected) {
                mControl.ChangePlaySpeed(speedFloat);
            }
            return true;
        });

        popup.show();
    }

    void init() {
        sIvRecord = findViewById(R.id.rotation);
        sSeekBar = findViewById(R.id.seekBar);
        mBtnPlay = findViewById(R.id.play);
        mBtnPre = findViewById(R.id.previous);
        mBtnNext = findViewById(R.id.next);
        sCurrentTv = findViewById(R.id.currenttime);
        sTotalTv = findViewById(R.id.totaltime);
        sTvName = findViewById(R.id.songTv);
        sTvSinger = findViewById(R.id.singerTv);
        mIvSmartHome = findViewById(R.id.smarthome);
        circleMenu = findViewById(R.id.circlemenu);
      //  mIvPlaySpeed = findViewById(R.id.ivplay_speed);
        mTvPlaySpeed = findViewById(R.id.tvplay_speed);
        mIvPlayMode = findViewById(R.id.ivplay_mode);
        mTvPlayMode = findViewById(R.id.tvplay_mode);
        mSmartHomeIv = findViewById(R.id.smarthome);
        mMapIv = findViewById(R.id.ivmap);
        mDeviceNum = findViewById(R.id.devices_number_Tv);
        mCurrentTimeTv = findViewById(R.id.mCurrentTimeTv);
        mIncreaseVolumeIv = findViewById(R.id.increase_volume_Iv);
        mReduceVolumeIv = findViewById(R.id.reduce_volume_Iv);
        mVolumeIv = findViewById(R.id.mVolumeIv);


        prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, @Nullable String key) {
                updateDeviceCount();
            }
        };
        // 注册监听器
        SharedPreferences sp = getSharedPreferences("deviceInfo", MODE_PRIVATE);
        sp.registerOnSharedPreferenceChangeListener(prefListener);
        updateDeviceCount();
        // 获取 AudioManager 实例
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        //获取当前日期
        Calendar calendar = Calendar.getInstance();
        //将日期转化为星期
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        String weekDay = sdf.format(calendar.getTime());
        //获取当前月份
        SimpleDateFormat sdp = new SimpleDateFormat("MMMM", Locale.getDefault());
        sdp.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        String Month = sdp.format(new Date());
        //获取当前日期
        SimpleDateFormat sdt = new SimpleDateFormat("dd");
        sdt.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        String day = sdt.format(calendar.getTime());
        //获取当前小时，分钟
        SimpleDateFormat sdh = new SimpleDateFormat("HH:mm");
        sdh.setTimeZone(TimeZone.getTimeZone("GMT+08"));
        String hour = sdh.format(calendar.getTime());
        String sTime = weekDay + "       " + Month + "   " + day + "       " + hour;
        mCurrentTimeTv.setText(sTime);
        circleMenu.setMainMenu(Color.parseColor("#CDCDCD"), R.drawable.menu, R.drawable.cancle)
                .addSubMenu(Color.parseColor("#88bef5"), R.drawable.playmode_sequential)
                .addSubMenu(Color.parseColor("#83e85a"), R.drawable.speed_1)
                .addSubMenu(Color.parseColor("#FF4B32"), R.drawable.speed_2)
                .addSubMenu(Color.parseColor("#ba53de"), R.drawable.speed_3)
                .addSubMenu(Color.parseColor("#ff8a5c"), R.drawable.speed_4)
                .setOnMenuSelectedListener(new OnMenuSelectedListener() {
                    @Override
                    public void onMenuSelected(int index) {
                        switch (index) {
                            case 0:
                                if (mPlayModeState == 0) {
                                    Toast.makeText(MainActivity.this, "切换为循环播放", Toast.LENGTH_SHORT).show();
                                    mIvPlayMode.setImageResource(R.drawable.playmode_loop);
                                    mTvPlayMode.setText("循环播放");
                                    mControl.setPlayMode(1);
                                    mPlayModeState = 1;
                                } else if (mPlayModeState == 1) {
                                    Toast.makeText(context, "切换为随机播放", Toast.LENGTH_SHORT).show();
                                    mIvPlayMode.setImageResource(R.drawable.playmode_shuffle);
                                    mTvPlayMode.setText("随机播放");
                                    mControl.setPlayMode(2);
                                    mPlayModeState = 2;
                                } else {
                                    Toast.makeText(context, "切换为顺序播放", Toast.LENGTH_SHORT).show();
                                    mIvPlayMode.setImageResource(R.drawable.playmode_sequential);
                                    mTvPlayMode.setText("顺序播放");
                                    mControl.setPlayMode(0);
                                    mPlayModeState = 0;
                                }

                                break;
                            case 1:
                                Toast.makeText(MainActivity.this, "0.5倍速", Toast.LENGTH_SHORT).show();
                                if (mControl != null && mIsServiceConnected) {
                                    mControl.ChangePlaySpeed(0.5f);
                                    mTvPlaySpeed.setText("0.5X");
                                    // 这里可以更新UI来显示当前倍速，如果你有这样的UI元素的话
                                }
                                break;
                            case 2:
                                Toast.makeText(MainActivity.this, "1倍速", Toast.LENGTH_SHORT).show();
                                if (mControl != null && mIsServiceConnected) {
                                    mControl.ChangePlaySpeed(1.0f);
                                    mTvPlaySpeed.setText("1.0X");
                                    // 这里可以更新UI来显示当前倍速，如果你有这样的UI元素的话
                                }
                                break;
                            case 3:
                                Toast.makeText(MainActivity.this, "1.5倍速", Toast.LENGTH_SHORT).show();
                                if (mControl != null && mIsServiceConnected) {
                                    mControl.ChangePlaySpeed(1.5f);
                                    mTvPlaySpeed.setText("1.5X");
                                    // 这里可以更新UI来显示当前倍速，如果你有这样的UI元素的话
                                }
                                break;
                            case 4:
                                Toast.makeText(MainActivity.this, "2倍速", Toast.LENGTH_SHORT).show();
                                if (mControl != null && mIsServiceConnected) {
                                    mControl.ChangePlaySpeed(2.0f);
                                    mTvPlaySpeed.setText("2.0X");
                                    // 这里可以更新UI来显示当前倍速，如果你有这样的UI元素的话
                                }
                                break;
                        }
                    }
                });
        mIvSmartHome.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, SmartHomeActivity.class);
            startActivity(intent);
        });

        mBtnPlay.setOnClickListener(v -> { //点击播放
            if (mControl != null) {
                if (mStateFlag == 0) {
                    //开始播放
                    mControl.play();
                    //轮盘转动
                    mAnimator.start();
                    mBtnPlay.setBackgroundResource(R.drawable.pause);
                    mStateFlag = 2; // 当前为播放状态
                } else if (mStateFlag == 2) {
                    //暂停播放
                    mControl.pause();
                    //轮盘转动
                    mAnimator.pause();
                    mBtnPlay.setBackgroundResource(R.drawable.play);
                    mStateFlag = 1; // 当前为暂停状态
                } else if (mStateFlag == 1) {
                    //继续播放
                    mControl.resume();
                    //轮盘转动
                    mAnimator.resume();
                    mBtnPlay.setBackgroundResource(R.drawable.pause);
                    mStateFlag = 2; // 当前为播放状态
                }
            } else {
                // 服务尚未连接
                Toast.makeText(MainActivity.this, "服务尚未连接", Toast.LENGTH_SHORT).show();
            }

        });

        mBtnPre.setOnClickListener(v -> { //点击上一首
            if (mIsServiceConnected && mControl != null) {
                int currentIndex = mControl.getCurrentIndex();
                int newIndex = (currentIndex - 1 + mControl.getSongCount()) % mControl.getSongCount(); // 循环播放
                mControl.changeSong(newIndex); // 调用MusicControl中的方法来切换歌曲
                //mSpinner.setSelection(1);
                if (mStateFlag == 2) {
                    mAnimator.start();
                    mControl.resume();

                } else if (mStateFlag == 1) {
                    mAnimator.pause();
                    mControl.pause();
                }
            }

        });
        mBtnNext.setOnClickListener(v -> { //点击下一首
            if (mIsServiceConnected && mControl != null) {
                int currentIndex = mControl.getCurrentIndex();
                int newIndex = (currentIndex + 1) % mControl.getSongCount();
                mControl.changeSong(newIndex);
                //mSpinner.setSelection(1);
                if (mStateFlag == 2) {
                    mAnimator.start();
                    mControl.resume();
                } else if (mStateFlag == 1) {
                    mAnimator.pause();
                    mControl.pause();
                }
            }
        });
        mSmartHomeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,SmartHomeActivity.class);
                startActivity(intent);
            }
        });
        mMapIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,MapActivity.class);
                startActivity(intent);
            }
        });
        mIncreaseVolumeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAudioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
            }
        });
        mReduceVolumeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAudioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
            }
        });
        mVolumeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(flagVolume == true){
                    mVolumeIv.setBackgroundResource(R.drawable.volume);
                    mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
                    flagVolume = false;
                }else {
                    flagVolume =true;
                    mVolumeIv.setBackgroundResource(R.drawable.mute);
                    mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
                }
            }
        });


        //设置图片动画的旋转参数
        mAnimator = ObjectAnimator.ofFloat(sIvRecord, "rotation", 0, 360.0F);
        mAnimator.setDuration(10000);
        mAnimator.setInterpolator(new LinearInterpolator());
        mAnimator.setRepeatCount(-1);

        //绑定服务
        Intent intent = new Intent(getApplicationContext(), MusicService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);

        //进度条变化的相关操作
        sSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //用户拖动
                if (fromUser) {
                    mControl.seekTo(progress);
                }
            }

            //拖动进度条过程中
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //拖动过程歌曲会暂停
                mControl.pause();
                mAnimator.pause();
                mBtnPlay.setBackgroundResource(R.drawable.play);
            }

            //松开进度条时
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mAnimator.resume();
                // 检查是否达到最大值，如果是则播放下一首歌曲
                if (seekBar.getProgress() == seekBar.getMax()) {
                    // 如果是单曲循环模式，并且达到了最大值，则手动切换到下一首歌
                        int currentIndex = mControl.getCurrentIndex();
                        int newIndex = (currentIndex + 1) % mControl.getSongCount();
                        mControl.changeSong(newIndex); // 调用MusicControl中的方法来切换歌曲

                    mBtnPlay.setBackgroundResource(R.drawable.pause); // 更新播放/暂停按钮状态
                    mStateFlag = 2; // 更新播放状态标志
                } else { // 如果不是最大值，则直接恢复播放
                    mControl.resume();
                    mBtnPlay.setBackgroundResource(R.drawable.pause); // 更新播放/暂停按钮状态
                    mStateFlag = 2;//??????
                }
            }
        });
    }

    //销毁时取消服务绑定
    @Override
    protected void onDestroy() {
        mControl.stop();
        if (mIsServiceConnected) {
            unbindService(serviceConnection);
        }
        super.onDestroy();
    }
    private void updateDeviceCount() {
        SharedPreferences sp = getSharedPreferences("deviceInfo", MODE_PRIVATE);
        boolean acOn = sp.getBoolean("acState", false);
        boolean soOn = sp.getBoolean("soState", false);
        boolean apOn = sp.getBoolean("apState", false);
        boolean huOn = sp.getBoolean("huState", false);
        int n = (acOn ? 1 : 0) + (soOn ? 1 : 0) + (apOn ? 1 : 0) + (huOn ? 1 : 0);
        mDeviceNum.setText(n + " Devices");
    }

    //将毫秒值转换为时间文本样式
    public static String msToMinSec(int ms) {
        int sec = ms / 1000;
        int min = sec / 60;
        sec -= min * 60;
        return String.format("%02d:%02d", min, sec);
    }
}